//
// Created by A4-28 on 2020/10/10.
//
#include <glad/glad.h>
#include <iostream>
#include "../camera/camera.h"
#include "../material/Shader.h"
#include "../utils/stb_image.h"
#include "../utils/Utils.h"
#include "../material/Material.h"


float cubeVertices[] = {
        // Back face
        -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // Bottom-left
        0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right
        0.5f, -0.5f, -0.5f, 1.0f, 0.0f, // bottom-right
        0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right
        -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // bottom-left
        -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left
        // Front face
        -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left
        0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-right
        0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // top-right
        0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // top-right
        -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, // top-left
        -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left
        // Left face
        -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-right
        -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-left
        -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-left
        -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-left
        -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-right
        -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-right
        // Right face
        0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-left
        0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-right
        0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right
        0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-right
        0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-left
        0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left
        // Bottom face
        -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // top-right
        0.5f, -0.5f, -0.5f, 1.0f, 1.0f, // top-left
        0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-left
        0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-left
        -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-right
        -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // top-right
        // Top face
        -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left
        0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // bottom-right
        0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right
        0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // bottom-right
        -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left
        -0.5f, 0.5f, 0.5f, 0.0f, 0.0f  // bottom-left
};
float planeVertices[] = {
        // positions          // texture Coords (note we set these higher than 1 (together with GL_REPEAT as texture wrapping mode). this will cause the floor texture to repeat)
        5.0f, -0.5f, 5.0f, 2.0f, 0.0f,
        -5.0f, -0.5f, 5.0f, 0.0f, 0.0f,
        -5.0f, -0.5f, -5.0f, 0.0f, 2.0f,

        5.0f, -0.5f, 5.0f, 2.0f, 0.0f,
        -5.0f, -0.5f, -5.0f, 0.0f, 2.0f,
        5.0f, -0.5f, -5.0f, 2.0f, 2.0f
};
float quadVertices[] = { // vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates.
        // positions   // texCoords
        -1.0f, 1.0f, 0.0f, 1.0f,
        -1.0f, -1.0f, 0.0f, 0.0f,
        1.0f, -1.0f, 1.0f, 0.0f,

        -1.0f, 1.0f, 0.0f, 1.0f,
        1.0f, -1.0f, 1.0f, 0.0f,
        1.0f, 1.0f, 1.0f, 1.0f
};
Utils *utilss = new Utils();
GlfwInit *init = new GlfwInit();
Camera camera1(
        glm::vec3(0, 0, 3.0f),
        glm::radians(0.0f),
        glm::radians(180.0f),
        glm::vec3(0, 1.0f, 0),
        0.0005,
        0.0005,
        45.0);

void camera1Move(GLFWwindow *w, double xPos, double yPos) {
    camera1.Movement(xPos, yPos);
}

void handleInput(GLFWwindow *w) {
    if (glfwGetKey(w, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
        glfwSetWindowShouldClose(w, true);
    }

    if (glfwGetKey(w, GLFW_KEY_A) == GLFW_PRESS) {
        camera1.SpeedX = -1.0f;
    } else if (glfwGetKey(w, GLFW_KEY_D) == GLFW_PRESS) {
        camera1.SpeedX = 1.0f;
    } else {
        camera1.SpeedX = 0.0f;
    }

    if (glfwGetKey(w, GLFW_KEY_W) == GLFW_PRESS) {
        camera1.SpeedZ = 1.0f;
    } else if (glfwGetKey(w, GLFW_KEY_S) == GLFW_PRESS) {
        camera1.SpeedZ = -1.0f;
    } else {
        camera1.SpeedZ = 0.0f;
    }

    if (glfwGetKey(w, GLFW_KEY_Q) == GLFW_PRESS) {
        camera1.SpeedY = 1.0f;
    } else if (glfwGetKey(w, GLFW_KEY_E) == GLFW_PRESS) {
        camera1.SpeedY = -1.0f;
    } else {
        camera1.SpeedY = 0.0f;
    }
}

void framebuffer_size_callback(GLFWwindow *window, int width, int height) {
    // make sure the viewport matches the new window dimensions; note that width and
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
}

const unsigned int SCR_WIDTH = 400;
const unsigned int SCR_HEIGHT = 400;

void TestDemo() {
    //初始化 glfw 版本以及core模式
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    //创建窗口
    GLFWwindow *window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "depthTest", NULL, NULL);
    if (window == NULL) {
        printf("create window error!!");
        glfwTerminate();
        return;
    }
    //context
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    //cursor 移动位置的回调
    glfwSetCursorPosCallback(window, camera1Move);
//    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    //初始glad
    if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) {
        printf("init glad error");
        glfwTerminate();
        return;
    }
    //视口设置
    glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
    //开启深度测试
    glEnable(GL_DEPTH_TEST);
    //线框模式
//    glPolygonMode(GL_FRONT_AND_BACK ,GL_LINE );

    Shader shader = Shader();
    unsigned int ID = shader.loadShader(utilss->GetResourceDir().append("\\resource\\frameBuffer\\vertex.glsl"),
                                        utilss->GetResourceDir().append("\\resource\\frameBuffer\\frag.glsl"));
    Shader screenShader = Shader();
    unsigned int screen = screenShader.loadShader(
            utilss->GetResourceDir().append("\\resource\\frameBuffer\\screen_vertex.glsl"),
            utilss->GetResourceDir().append("\\resource\\frameBuffer\\screen_frag.glsl"));
    unsigned int cubeVAO, cubeVBO;
    glGenVertexArrays(1, &cubeVAO);
    glGenBuffers(1, &cubeVBO);
    glBindVertexArray(cubeVAO);
    glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void *) 0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void *) (3 * sizeof(float)));
    // plane VAO
    unsigned int planeVAO, planeVBO;
    glGenVertexArrays(1, &planeVAO);
    glGenBuffers(1, &planeVBO);
    glBindVertexArray(planeVAO);
    glBindBuffer(GL_ARRAY_BUFFER, planeVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void *) 0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void *) (3 * sizeof(float)));

    // screen quad VAO
    unsigned int quadVAO, quadVBO;
    glGenVertexArrays(1, &quadVAO);
    glGenBuffers(1, &quadVBO);
    glBindVertexArray(quadVAO);
    glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void *) 0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void *) (2 * sizeof(float)));

    unsigned int a = utilss->loadTexture(utilss->GetResourceDir().append("\\resource\\container2.png").c_str());
    unsigned int b = utilss->loadTexture(utilss->GetResourceDir().append("\\resource\\metal.png").c_str());

    glm::mat4 model;
    glm::mat4 view;
    glm::mat4 project;

    /**
     * 颜色值的颜色缓冲，深度值的深度缓冲，丢弃片段的模板缓冲，这些缓冲结合起来叫做帧缓冲(Framebuffer)，它被储存在内存中
     */
    //frameBuffer
    unsigned int framebuffer;
    glGenFramebuffers(1, &framebuffer);//创建帧缓存
    /**
     * GL_FRAMEBUFFER 读写都会影响
     * GL_READ_FRAMEBUFFER   会使用在所有像是glReadPixels的读取操作中
     * GL_DRAW_FRAMEBUFFER   会被用作渲染、清除等写入操作的目标
     */
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);//绑定当前帧缓存
    /**
     * 完整帧缓冲
     *  1.附加至少一个缓冲（颜色、深度或模板缓冲）
     *  2.至少有一个颜色附件(Attachment)。
     *  3.所有的附件都必须是完整的（保留了内存）。
     *  4.每个缓冲都应该有相同的样本数。
     */

    /**
     * 当把一个纹理附加到帧缓冲的时候，所有的渲染指令将会写入到这个纹理。
     * 所有渲染操作都会写入这个纹理中，方便着手器中进行使用
     */
    unsigned int textureColorbuffer;
    glGenTextures(1, &textureColorbuffer);
    glBindTexture(GL_TEXTURE_2D, textureColorbuffer);
    /**
     * 纹理类型--
     * https://blog.csdn.net/csxiaoshui/article/details/27543615
     *  void glTexImage2D(
          GLenum   target,  指定纹理单元的类型
          GLint   level, 指定纹理单元的层次，非mipmap纹理level设置为0，mipmap纹理设置为纹理的层级
          GLint   internalFormat, 指定OpenGL是如何管理纹理单元中数据格式的
          GLsizei   width,
          GLsizei   height,
          GLint   border, 指定纹理单元的边框，如果包含边框取值为1，不包含边框取值为0
          GLenum   format, 指定data所指向的数据的格式
          GLenum   type, 指定data所指向的数据的类型
          const GLvoid *   data 实际指向的数据是什么
        );
     */
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, SCR_WIDTH, SCR_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
    //不用关心环绕方式和过滤方式(多级渐远)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    /**
     * 将纹理附加到帧缓冲上
     * 参数1：绘制目标
     * 参数2：添加的附件类型
     * 参数3：附件添加的纹理类型
     * 参数4：希望添加的纹理
     * 参数5：多级渐远级别
     */
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureColorbuffer, 0);
    //如果你想将你的屏幕渲染到一个更小或更大的纹理上，你需要（在渲染到你的帧缓冲之前）再次调用glViewport，使用纹理的新维度作为参数，否则只有一小部分的纹理或屏幕会被渲染到这个纹理上

    /**
     * 渲染缓冲对象
     * 渲染缓冲对象是一个真正的缓冲，即一系列的字节、整数、像素等。渲染缓冲对象附加的好处是，它会将数据储存为OpenGL原生的渲染格式，它是为离屏渲染到帧缓冲优化过的
     *
     * 渲染缓冲对象直接将所有的渲染数据储存到它的缓冲中，不会做任何针对纹理格式的转换，让它变为一个更快的可写储存介质。
     * 渲染缓冲对象能为你的帧缓冲对象提供一些优化，但知道什么时候使用渲染缓冲对象，什么时候使用纹理是很重要的。
     * 通常的规则是，如果你不需要从一个缓冲中采样数据，那么对这个缓冲使用渲染缓冲对象会是明智的选择。
     * 如果你需要从缓冲中采样颜色或深度值等数据，那么你应该选择纹理附件
     */
    unsigned int rbo;
    glGenRenderbuffers(1, &rbo);
    glBindRenderbuffer(GL_RENDERBUFFER, rbo);
    //创建深度和模板渲染缓冲对象
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, SCR_WIDTH, SCR_HEIGHT);
    //渲染缓冲对象附加到当前帧缓冲
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo);
    //帧缓冲是否完整
    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
        std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl;
    }
    //再次激活默认帧缓冲 绑定为0
//    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    //完成所有帧缓冲操作后删除
    //glDeleteFramebuffers(1, &fbo);

    //  够以一个纹理图像的方式访问已渲染场景中的每个像素
    glUniform1i(glGetUniformLocation(screen,"ourTexcoord"),0);
    //渲染
    while (!glfwWindowShouldClose(window)) {
        handleInput(window);

        //绑定
        glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
        glEnable(GL_DEPTH_TEST);


        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glUseProgram(ID);

        model = glm::mat4(1.0f);
        view = camera1.GetViewMatrix();
        project = glm::perspective(glm::radians(camera1.FOV), (float) 800 / (float) 800, 0.1f, 100.0f);

        glUniformMatrix4fv(glGetUniformLocation(ID, "view"), 1, false, glm::value_ptr(view));
        glUniformMatrix4fv(glGetUniformLocation(ID, "project"), 1, false, glm::value_ptr(project));

        // floor
        glBindVertexArray(planeVAO);
        model = glm::mat4(1.0f);
        glBindTexture(GL_TEXTURE_2D, b);
        glUniformMatrix4fv(glGetUniformLocation(ID, "model"), 1, false, glm::value_ptr(model));
        glDrawArrays(GL_TRIANGLES, 0, 6);

        // cubes
        glBindVertexArray(cubeVAO);
        model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f));
        glBindTexture(GL_TEXTURE_2D, a);
        glUniformMatrix4fv(glGetUniformLocation(ID, "model"), 1, false, glm::value_ptr(model));
        glDrawArrays(GL_TRIANGLES, 0, 36);
        model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f));
        glUniformMatrix4fv(glGetUniformLocation(ID, "model"), 1, false, glm::value_ptr(model));
        glDrawArrays(GL_TRIANGLES, 0, 36);


        //解绑使用默认的帧缓冲
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
        glDisable(GL_DEPTH_TEST);
        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        //
        glUseProgram(screen);
        glBindVertexArray(quadVAO);
        //将之前填充帧缓冲的纹理绘制到屏幕
        glBindTexture(GL_TEXTURE_2D, textureColorbuffer);
        glDrawArrays(GL_TRIANGLES, 0, 6);


        glfwPollEvents();
        glfwSwapBuffers(window);
        camera1.UpdateCameraPosition();
    }
    glfwTerminate();
}

int main() {
    TestDemo();
}